/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("cw_djlc_wlzb",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.Finance.IServices;
using VOL.Core.Filters;
using VOL.Core.Extensions;
using VOL.Finance.Services;
using VOL.Core.Utilities;
using VOL.Core.DBManager;
using VOL.Core.ManageUser;
using System.Linq;

namespace VOL.Finance.Controllers
{
    public partial class cw_djlc_wlzbController
    {
        private readonly Icw_djlc_wlzbService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly cw_djlc_wlzbService cw_djlc_wlzbService;

        [ActivatorUtilitiesConstructor]
        public cw_djlc_wlzbController(
            Icw_djlc_wlzbService service,
            IHttpContextAccessor httpContextAccessor,
            cw_djlc_wlzbService cw_djlc_wlzbService
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
            this.cw_djlc_wlzbService = cw_djlc_wlzbService;
        }
        [ApiActionPermission()]//权限重写，在控制器中增加
        public override ActionResult Update([FromBody] SaveModel saveModel)
        {
            
            return base.Update(saveModel);

        }
        [ApiActionPermission()]//权限重写，在控制器中增加
        public override ActionResult Import(List<IFormFile> fileInput)
        {
            return base.Import(fileInput);
        }

        [ApiActionPermission()]//权限重写，在控制器中增加
        public override ActionResult GetPageData([FromBody] PageDataOptions loadData)
        {
            return base.GetPageData(loadData);
        }

        /// <summary>
        /// 下载模板一致
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("DownLoadTemplate1")]
        [ApiActionPermission()]//权限重写，在控制器中增加
        public ActionResult DownLoadTemplate1()
        {
            return base.DownLoadTemplate();
        }

        /// <summary>
        /// 导入时加参数
        /// </summary>
        /// <param name="fileInput"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpGet, HttpPost, Route("Import1")]
        [ApiActionPermission()]//权限重写，在控制器中增加
        public ActionResult Import1(List<IFormFile> fileInput,string parameter)
        {
            WebResponseContent webResponse = new WebResponseContent();
            if (parameter.IsNullOrEmpty())
            {
                return Json(webResponse.Error("参数ID不能为空，请检查！"));
            }
            cw_djlc_djzb djzb = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(x => x.cw_djlc_code == parameter).FirstOrDefault();
            string oldmaterialnum = "";
            int count = 0;
            if (djzb != null)
            {
                oldmaterialnum = djzb.oldmaterialnum;//对标物料号；
                //导入前先通过对标物料号，查看物料主表里到底有没有这个BOM：如果有直接不让导入并且查到这个BOM编号；如果没有创建一个旧的BOM编号
                count = DBServerProvider.DbContext.Set<cw_djlc_wlzb>().Where(s => s.materialnum == oldmaterialnum).Count();
            }
            if (count>1) //有BOM不需要进行导入操作，直接赋值就可以了
            {
                cw_djlc_wlzb wlzb = DBServerProvider.DbContext.Set<cw_djlc_wlzb>().Where(w => w.materialnum == oldmaterialnum).FirstOrDefault();
                if (wlzb!=null)
                {
                    djzb.oldbomnumber = wlzb.bomnumber;
                    DBServerProvider.DbContext.Set<cw_djlc_djzb>().Update(djzb);
                    DBServerProvider.DbContext.SaveChanges();
                }
                return Json(webResponse.OK("该对标物料号已存在BOM，无需再导入！"));
            }
            else
            {
                return Json(cw_djlc_wlzbService.Import1(fileInput, parameter));
            }
            
        }

        [ApiActionPermission()]
        [HttpPost, Route("updateWlzbBySAPBOM")]//,AllowAnonymous
        public ActionResult updateWlzbBySAPBOM(string cw_djlc_djzb_id)
        {
            WebResponseContent webResponse = new WebResponseContent();
            var dapper = DBServerProvider.SqlDapper;
            if (string.IsNullOrEmpty(cw_djlc_djzb_id))
            {
                return Json(webResponse.Error("数据不能为空,请检查！"));
            }
            fk_reimtask task = DBServerProvider.DbContext.Set<fk_reimtask>().Where(s => s.stepid == 10 && s.reimid == Guid.Parse(cw_djlc_djzb_id)).FirstOrDefault();
            if (task == null)
            {
                return Json(webResponse.Error("数据不能为空，请联系管理员！"));
            }
            cw_djlc_djzb djzb = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(s => s.cw_djlc_djzb_id == Guid.Parse(cw_djlc_djzb_id)).FirstOrDefault();
            string oldbomnumber = "";
            string cw_djlc_code = "";
            if (djzb != null)
            {
                oldbomnumber = djzb.oldbomnumber;
                cw_djlc_code = djzb.cw_djlc_code;
            }
            int total1 = 0 , total2 = 0;
            if (!string.IsNullOrEmpty(cw_djlc_code))
            {
                
                total1 = DBServerProvider.DbContext.Set<cw_djlc_analyze_table>().Where(s => s.cw_djlc_code == cw_djlc_code).Count();
                total2 = DBServerProvider.DbContext.Set<cw_djlc_analyze_total_table>().Where(s => s.cw_djlc_code == cw_djlc_code).Count();
            }
            try
            {
                dapper.BeginTrans();
                //修改产品定价流程主表同步bom的字段
                string sql = "update cw_djlc_djzb set synchronizationbomstatus = 0 ,synchronizationpricestatus = 0 where cw_djlc_djzb_id = @value";
                var data = dapper.ExcuteNonQuery(sql, new { value = cw_djlc_djzb_id });
                //删除当前产品定价流程的物料bom表
                sql = "delete from cw_djlc_wlzb where cw_djlc_djzb_id = @value";
                var data2 = dapper.ExcuteNonQuery(sql, new { value = cw_djlc_djzb_id });
                //删除当前产品定价流程的物料价格维护表
                sql = "delete from cw_djlc_wljgwh where cw_djlc_djzb_id = @value";
                var data3 = dapper.ExcuteNonQuery(sql, new { value = cw_djlc_djzb_id });

                sql = "delete from cw_djlc_analyze_table where cw_djlc_djzb_id = @value";
                var data4 = dapper.ExcuteNonQuery(sql, new { value = cw_djlc_djzb_id });

                sql = "delete from cw_djlc_analyze_total_table where cw_djlc_djzb_id = @value";
                var data5 = dapper.ExcuteNonQuery(sql, new { value = cw_djlc_djzb_id });
                if (total1 > 0 || total2 > 0)
                {
                    sql = "update cw_djlc_wlzb set is_synchronization_status = 0 where bomnumber = @value";
                    var data6 = dapper.ExcuteNonQuery(sql, new { value = oldbomnumber });
                }
                sql = "delete from cw_djlc_configuration_tradition where cw_djlc_djzb_id = @value";
                var data7 = dapper.ExcuteNonQuery(sql, new { value = cw_djlc_djzb_id });
                sql = "delete from cw_djlc_configuration_new_energy where cw_djlc_djzb_id = @value";
                var data8 = dapper.ExcuteNonQuery(sql, new { value = cw_djlc_djzb_id });
                /*
                //修改当前流程节点 类似杨艳操作人信息修改： 回退到起点 fk_reimtask 
                sql = "update fk_reimtask set ishandled = 1 ,reyijian = 'SAPBOM变更，回退起点',handledtime = @date where ishandled = 0 and cw_djlc_djzb_id = @value and to_username = @username";
                var data4 = dapper.ExcuteNonQuery(sql, new { date = new DateTime(), value = cw_djlc_djzb_id , username  = UserContext.Current.UserId });
                //添加一条新的task记录

                sql = "insert into fk_reimtask(path_router,menuname,createtime,to_username,to_userrealname,ishandled,reimid,stepid,stepname,reimtable)values" +
                    "(@path_router,@menuname,@createtime,@to_username,@to_userrealname,@ishandled,@reimid,@stepid,@stepname,@reimtable)";
                var data5 = dapper.ExcuteNonQuery(sql, new { path_router = task.path_router,   date = new DateTime(), value = cw_djlc_djzb_id, username = UserContext.Current.UserId });

                //流程图修改
                sql = "update fk_reimtask set ishandled = 1 ,reyijian = 'SAPBOM变更，回退起点',handledtime = @date where ishandled = 0 and cw_djlc_djzb_id = @value and to_username = @username";
                var data6 = dapper.ExcuteNonQuery(sql, new { date = new DateTime(), value = cw_djlc_djzb_id, username = UserContext.Current.UserId });*/

                dapper.Commit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                dapper.Rollback();
                return Json(webResponse.Error("SAPBOM变更-不成功，请重新再试！"));
            }

            return Json(webResponse.OK("SAPBOM变更-成功！"));
        }
        [ApiActionPermission()]//权限重写，在控制器中增加
        public override ActionResult Del([FromBody] object[] keys)
        {
            return base.Del(keys);
        }
        [ApiActionPermission()]//权限重写，在控制器中增加
        public override ActionResult Add([FromBody] SaveModel saveModel)
        {
            return base.Add(saveModel);
        }
    }
}
